<?php
//endnight and begin night indicate when we show the moon or sun. Use military time and only indicate the hour.
$endnight    = 7;
$beginnight = 19;
//urlencode will make sure special characters (like a space) are handled without error.
$location    = urlencode($_GET['location']);

//Get the source of the xml file and read it
$xmlfile = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=$location";
$xmlparser = xml_parser_create();
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);
//Parse the info into an array.
xml_parse_into_struct($xmlparser,$xmldata,$values,$ind);
xml_parser_free($xmlparser);

//Create an array with just the "important" stuff.
$important     = Array(
Location    => $values[17]["value"],
Weather        => $values[72]["value"],
TempF        => $values[76]["value"],
TempC        => $values[78]["value"],
Humidity    => $values[80]["value"],
WindDir        => $values[84]["value"],
Wind        => $values[88]["value"]
);

//This will determine if it's day or night. It's not used in this script, but can be used to choose either the moon or sun for images.
if(date('H') < $endnight or date('H') > $beginnight)
    $day = false;
else
    $day = true;

//Check to make sure the location is valid. Wunderground will still return some fields even if the location doesn't exist, so we
//Want to make sure the location is at least 4 characters long.
if(strlen($important['Location']) < 4)
    echo "That location was not found. Please try again.";
else
{
    //Finally, print out the important information.
    echo "Location: ".$important['Location']."<br/>";
    echo "Conditions: ".$important['Weather']."<br/>";
    echo "Temperature: ".$important['TempF']." F<br/>";
    echo "Humidity: ".$important['Humidity']." %<br/>";
    echo "Wind: ".$important['Wind']." MPH from ".$important['WindDir']."<br/>";

    //Remember to credit Wunderground with the info. Otherwise they may ban your use. I have it commented for now.
    //echo 'Weather by <a href="http://www.wunderground.com/" target="_new">WUnderground</a>';
}
?>